package com.imooc.distributedemo;

import java.sql.*;

public class DbConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/db_taoke";
        String username = "root";
        String password = "abcd1234";

        try {
            // 手动加载驱动（通常不推荐，因为JDBC 4.0之后可以自动加载）
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, username, password);
            System.out.println("Connected to the database!");
            conn.close(); // 关闭连接
        } catch (ClassNotFoundException e) {
            System.out.println("Driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Connection failed!");
            e.printStackTrace();
        }


        // 连接到数据库
        try (Connection conn = DriverManager.getConnection(url, username, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM t_order_item")) {

            System.out.println("Connected to the database successfully.");

            // 处理查询结果
            while (rs.next()) {
                System.out.println("ID: " + rs.getLong("id"));
                System.out.println("Order ID: " + rs.getLong("order_id"));
                System.out.println("Product ID: " + rs.getLong("product_id"));
                System.out.println("Count: " + rs.getInt("count"));
                System.out.println("Description: " + rs.getString("description"));
                System.out.println("-------------------------------");
            }
        } catch (SQLException e) {
            System.out.println("Error connecting to the database.");
            e.printStackTrace();
        }
    }
}
